package com.sand.controller;

import com.alibaba.fastjson.JSON;
import com.sand.entity.TRoleEntity;
import com.sand.entity.TUserEntity;
import com.sand.service.IAuthService;
import com.sand.service.IRoleService;
import com.sand.service.IUserInfoService;
import com.sand.service.IUserService;
import com.sand.util.ModelTest;
import com.sand.util.PageModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping(value = "user")
public class UserController {
/**
 *用户接口
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/11/26/026 14:40
 */
    //userService接口
    @Resource(name = "userService")
    private IUserService userService;
    //authService接口
    @Resource(name = "authService")
    private IAuthService authService;
    //roleService接口
    @Resource(name = "roleService")
    private IRoleService roleService;
    //IUserInfoService接口
    @Resource(name = "iUserInfoService")
    private IUserInfoService iUserInfoService;

    //验证码
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public void getCode(HttpServletRequest request,HttpServletResponse response)throws Exception{

        //创建底图
        ImageIcon imageIcon = new ImageIcon(request.getServletContext().getRealPath("layui/images/bg.jpg"));
        //System.out.println(imageIcon.getIconHeight()+"||"+imageIcon.getIconWidth());
        //创建画布|宽|高|背景样式
        BufferedImage bufferedImage = new BufferedImage(100,46,BufferedImage.TYPE_4BYTE_ABGR);
        //创建画笔
        Graphics graphics = bufferedImage.getGraphics();
        //画背景图片|图片|x起始位置|y起始位置|是否覆盖
        graphics.drawImage(imageIcon.getImage(),0,0,null);
        //创建内容
        String str="abcdefghijkmnopqrstuvwxzyABCDEFGHJKLMNPQRSTUVWXYZ123456789";
        //创建随机数对象
        Random rd = new Random();
        //获得随机数
        StringBuffer strCode = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            strCode.append(str.charAt(rd.nextInt(str.length())));
        }
        //将验证码存入session
        HttpSession session = request.getSession();
        String s = strCode.toString().toLowerCase();
        session.setAttribute("code",s);
        session.setAttribute("codeTime",new Date().getTime());
        //设置画笔颜色
        graphics.setColor(Color.black);
        //设置画笔字体
        graphics.setFont(new Font("楷体",Font.BOLD,35));
        //画字符|字符|x起始位置|y起始位置
        graphics.drawString(strCode.toString(),10,40);
        //设置线条
        for (int i = 0; i < 10; i++) {
            graphics.setColor(Color.red);
            int x1=rd.nextInt(imageIcon.getIconWidth());
            int y1=rd.nextInt(imageIcon.getIconHeight());

            int x2=rd.nextInt(imageIcon.getIconWidth());
            int y2=rd.nextInt(imageIcon.getIconHeight());
            //将两个点连接起来
            graphics.drawLine(x1,y1,x2,y2);
        }
        //输出图片|输出内容|输出格式|输入方式
        ImageIO.setUseCache(false);//设置内存缓存--》取消文件目录缓存
        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
    }
    //用户登录
    @RequestMapping(value = "/loginUser",method = RequestMethod.POST)
    public void loginUser(String name,String pwd,String yzm,HttpServletRequest request,HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();

        long codeTime = (long) session.getAttribute("codeTime");
        long time = new Date().getTime();
        String s=yzm.toLowerCase();
        if((time-codeTime)/1000>15){
            out.write("TimeOut");
        }else{
            String code=session.getAttribute("code").toString();
            if(!s.equals(code)){
                out.write("ERR");
            }else{
               TUserEntity user = userService.queryUserByNamePwd(name,pwd);
                if(user!=null){
                    session.setAttribute("user",user);
                    out.write("OK");
                }else{
                    out.write("NO");
                }
            }
        }
    }
    //用户登录权限查询
    @RequestMapping(value = "/hello")
    public void hello(HttpServletRequest request,HttpServletResponse response)throws Exception {
        HttpSession session = request.getSession();
        response.setCharacterEncoding("UTF-8");

        TUserEntity user = (TUserEntity) session.getAttribute("user");
        String str = authService.queryAuthByUser(user,request);

        response.getWriter().write(str);
    }
    //分页查询用户
    @RequestMapping(value = "/queryUserLimit")
    public void queryUserLimit(int limit,int page,String condition,HttpServletRequest request,HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");

        PageModel<TUserEntity> pm = userService.queryUserLimit(limit, page, condition);
        ModelTest<List<TUserEntity>> listData = new ModelTest<List<TUserEntity>>("OK",pm.getList(),0, pm.getPagecount());
        //查询所有角色
        List<TRoleEntity> roleList = roleService.queryRoleAll();
        request.getSession().setAttribute("roleList",roleList);
        response.getWriter().write(JSON.toJSON(listData).toString());
    }
    //删除用户
    @RequestMapping(value = "/delUser")
    public void delUser(String data,HttpServletResponse response)throws Exception{
        boolean bln = userService.delUser(data);
        if(bln){
            response.getWriter().write("OK");
        }else{
            response.getWriter().write("NO");
        }
    }
    //添加用户
    @RequestMapping(value = "/addUser")
    public void addUser(String data,HttpServletResponse response)throws Exception{
        boolean bln = userService.addUser(data);
        if(bln){
            response.getWriter().write("OK");
        }else{
            response.getWriter().write("NO");
        }
    }
    //根据id查询用户
    @RequestMapping(value = "/queryUserById")
    public ModelAndView queryUserById(int rid){
        TUserEntity user = userService.queryUserById(rid);
        return new ModelAndView("/layui/page/table/edit_user").addObject("upUser",user);
    }
    //修改用户
    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    public void updateUser(String data,HttpServletResponse response)throws Exception{
        boolean bln = userService.updateUser(data);
        if(bln){
            response.getWriter().write("OK");
        }else{
            response.getWriter().write("NO");
        }
    }
}
